// Copyright IBM Corp. 2014,2018. All Rights Reserved.
// Node module: loopback
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
/**
 * @param {import("loopback").LoopBackApplication } app
 */
module.exports = function (app) {

  'use strict';
  var loopback = require('loopback');
  /**
 * @type {typeof import("loopback").PersistedModel } 
 */
  var CartItem = loopback.Model.extend('CartItem', {
    tax: { type: Number, default: 0.1 },
    price: Number,
    item: String,
    qty: { type: Number, default: 20 },
    cartId: Number,
  });
  app.model(CartItem, { dataSource: 'db' })
  CartItem.sum = function (cartId, callback) {
    this.find({ where: { cartId: cartId } }, function (err, items) {
      if (err) return callback(err);
      var total = items
        .map(function (item) {
          return item.total();
        })
        .reduce(function (cur, prev) {
          return prev + cur;
        }, 0);

      callback(null, total);
    });
  };

  CartItem.remoteMethod('sum',
    {
      accepts: { arg: 'cartId', type: 'number' },
      returns: { arg: 'total', type: 'number' },
    }
  );

  CartItem.prototype.total = function () {
    return this.price * this.qty * (1 + this.tax);
  };
}